package com.swotxu.oldwebproject.redis;

import com.swotxu.oldwebproject.redis.conf.RedisConfig;
import com.swotxu.oldwebproject.redis.connection.IRedisConnection;
import com.swotxu.oldwebproject.redis.connection.impl.RedisConnection;
import com.swotxu.oldwebproject.redis.listener.JedisPubSubRegistor;
import com.swotxu.oldwebproject.redis.utils.RedisPropertiesUtil;
import com.swotxu.oldwebproject.session.utils.RedisSessionUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import redis.clients.jedis.JedisPool;

/**
 * redis管理工具类，可用于获取redis连接
 *
 * @Date: 2021/3/24 0024 13:35
 * @Author: swotxu
 */
public class RedisManager {
    private static final Logger LOGGER = LoggerFactory.getLogger(RedisPropertiesUtil.class);

    private static JedisPool jedisPool;

    static {
        // 初始化 jedisPool
        if (RedisPropertiesUtil.isEnable()) {
            LOGGER.info("\n ===== redis init begin ===== " +
                    "\n 1、初始化 jedisPool" +
                    "\n 2、注册 redis listenter" +
                    "\n 3、注册当前服务器 idcard" +
                    "\n ===== redis init end ===== ");
            RedisConfig redisCofig = RedisPropertiesUtil.getRedisCofig();
            jedisPool = new JedisPool(redisCofig.getConnectionConfig(),
                    redisCofig.getHost(), redisCofig.getPort(),
                    redisCofig.getTimeOut(), StringUtils.isNotBlank(redisCofig.getPassword())? redisCofig.getPassword() : null,
                    redisCofig.getDatabase());
            // 注册 redis相关服务 todo 暂时废弃
            // registerServers();
        } else {
            LOGGER.info("Not using redis!");
        }
    }

    /**
     * 注册 redis相关服务
     */
    private static void registerServers(){
        RedisConfig redisCofig = RedisPropertiesUtil.getRedisCofig();
        // 注册 redis 监听
        JedisPubSubRegistor.register(String.valueOf(redisCofig.getDatabase()));
        // 注册当前服务器 idcard
        RedisSessionUtil.registrationCurrentServer();
    }

    public static IRedisConnection getIRedisConnection() {
        return RedisConnection.getInstance();
    }

    public static JedisPool getJedisPool() {
        return jedisPool;
    }
}
